package com.example.test.schedule;

import cn.hutool.core.util.StrUtil;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class ScheduleController {

    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private final AtomicInteger ID = new AtomicInteger(0);
    private final Map<Integer, ScheduledFuture<?>> FUTURES = new ConcurrentHashMap<>();

    @GetMapping("/cron/start")
    public void startCronTask(String cron) {
        if (StrUtil.isBlank(cron))
            cron = "0/5 * * * * ?";
        int id = ID.incrementAndGet();
        ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(() -> {
            System.out.printf("执行定时任务: id=%d, currentTime=%d%n", id, System.currentTimeMillis());
        }, new CronTrigger(cron));

        FUTURES.put(id, future);
    }

    @GetMapping("/cron/stop/{id}")
    public void stopCronTask(@PathVariable int id) {
        ScheduledFuture<?> future = FUTURES.get(id);
        if (future != null) {
            future.cancel(true);
            FUTURES.remove(id);
        }
    }
}
